package cn.tjad.tjad2.module.user.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.qiandian.android.base.activity.BaseActivity;
import com.qiandian.android.base.common.bean.CommonBean;
import com.qiandian.android.base.common.utils.JsonUtils;
import com.qiandian.android.base.net.http.HttpConstants;
import com.qiandian.android.base.net.http.IDataCallBack;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.tjad.tjad2.BuildConfig;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.application.TjadApplication;
import cn.tjad.tjad2.business.RemoteDataService;
import cn.tjad.tjad2.cache.SPCacheManager;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.LoginBean;
import cn.tjad.tjad2.data.session.Session;
import cn.tjad.tjad2.net.fileupload.FileUploader;
import cn.tjad.tjad2.push.PushMessageId;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.EncryUtils;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.Tools;

@Route(path = PageId.LOGIN)
public class LoginActivity extends BaseActivity implements IDataCallBack {

    @BindView(R.id.login_input_account)
    EditText accountET;
    @BindView(R.id.login_input_pwd)
    EditText pwdET;
    @BindView(R.id.auto_login_checkbox)
    CheckBox autoLoginCB;
    @BindView(R.id.keep_pwd_checkbox)
    CheckBox keepPwdCB;
    @BindView(R.id.clear_pwd)
    ImageView clearPwd;
    @BindView(R.id.login_user_head)
    ImageView userHeadIV;
    @BindView(R.id.login_user_name)
    TextView userNameTV;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        init();
    }

    private void init() {
        pwdET.addTextChangedListener(passwordInputWatcher);
        accountET.addTextChangedListener(accountInputWatcher);
        SPCacheManager cacheManager = TjadApplication.getInstance().getSpCacheManager();
        boolean keepPwd = cacheManager.getBoolean(Keys.KEEP_PASSWORD, false);
        boolean autoLogin = cacheManager.getBoolean(Keys.AUTO_LOGIN, false);
        keepPwdCB.setChecked(keepPwd);
        autoLoginCB.setChecked(autoLogin);
        String account = EncryUtils.getInstance().decryptString(cacheManager.getString(Keys.USER_ACCOUNT), BuildConfig.ENCRYPT_KEY);
        String password = EncryUtils.getInstance().decryptString(cacheManager.getString(Keys.PASSWORD), BuildConfig.ENCRYPT_KEY);
        if (!TextUtils.isEmpty(account)) {
            accountET.setText(account);
            accountET.setTag(account);
        }
        if (!TextUtils.isEmpty(password) && keepPwd) {
            pwdET.setText(password);
        }
        if (TextUtils.isEmpty(pwdET.getText().toString())) {
            clearPwd.setVisibility(View.GONE);
        } else {
            clearPwd.setVisibility(View.VISIBLE);
        }
        String sessionString = cacheManager.getString(Keys.SESSION);
        if (sessionString != null) {
            LoginBean loginBean = JsonUtils.parseObject(sessionString, LoginBean.class);
            if (loginBean != null) {
                String name = loginBean.name;
                userNameTV.setText(name);
                userNameTV.setTag(name);
            }
        }
        if (autoLogin) {
            submitLogin();
        }
    }

    @OnClick(R.id.login_submit)
    public void onLoginClick(View view) {
        switch (view.getId()) {
            case R.id.login_submit:
                submitLogin();
                break;
        }
    }

    @OnClick({R.id.clear_pwd})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.clear_pwd:
                pwdET.setText("");
                break;
        }
    }

    @OnCheckedChanged(R.id.password_switch)
    public void onCheckedChanged(CompoundButton button, boolean value) {
        if (value) {
            pwdET.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        } else {
            pwdET.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }
    }

    private void submitLogin() {
        String account = accountET.getText().toString().trim();
        String password = pwdET.getText().toString();
        if (TextUtils.isEmpty(account)) {
            Tools.showToast("请输入账号!");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Tools.showToast("请输入密码!");
            return;
        }
        ProgressDialogUtils.show(this, "正在登录...");
        RemoteDataService.login(account, password, this);
    }

    @Override
    public boolean onReceiveError(int httpId, int errorCode, String errorMsg) {
        ProgressDialogUtils.dismiss();
        if (!TextUtils.isEmpty(errorMsg)) {
            Tools.showToast(errorMsg);
        }
        return false;
    }

    @Override
    public void onDataRefresh(int httpId, Object responseBean) {
        CommonBean<LoginBean> bean = (CommonBean<LoginBean>) responseBean;
        if (bean.resCode == HttpConstants.CODE_SUCCESS) {
            onLoginSuccess(bean.result);
        } else {
            Tools.showToast(bean.respMsg);
        }
        ProgressDialogUtils.dismiss();
    }

    private void onLoginSuccess(LoginBean bean) {
        Session session = new Session();
        session.setLoginInfo(bean);
        TjadApplication.getInstance().setSession(session);
        session.setAccount(accountET.getText().toString().trim());
        session.setPassword(pwdET.getText().toString());
        //设置推送信息
        JPushInterface.setAlias(this, PushMessageId.SET_ALIGN, session.getAccount());
        JPushInterface.setMobileNumber(this, PushMessageId.SET_PHONE_NUMBER, bean.phone);
        String department = null;
        if (bean.department != null) {
            department = bean.department.name;
        }
        if (!TextUtils.isEmpty(department)) {
            Set<String> tags = new HashSet<>();
            tags.add(department);
            JPushInterface.setTags(this, PushMessageId.SET_TAG, tags);
        }

        FileUploader.getInstance().setSession(bean.token.token);
        SPCacheManager cacheManager = TjadApplication.getInstance().getSpCacheManager();
        cacheManager.putString(Keys.SESSION, bean.toString());
        cacheManager.putBoolean(Keys.KEEP_PASSWORD, keepPwdCB.isChecked());
        cacheManager.putBoolean(Keys.AUTO_LOGIN, autoLoginCB.isChecked());
        String account = accountET.getText().toString().trim();
        cacheManager.putString(Keys.USER_ACCOUNT, EncryUtils.getInstance().encryptString(account, BuildConfig.ENCRYPT_KEY));
        if (keepPwdCB.isChecked()) {
            String password = pwdET.getText().toString();
            cacheManager.putString(Keys.PASSWORD, EncryUtils.getInstance().encryptString(password, BuildConfig.ENCRYPT_KEY));
        } else {
            cacheManager.remove(Keys.PASSWORD);
        }
        RouteUtils.toPage(this, PageId.PROJECT_LIST, null);
        finish();
    }

    private TextWatcher accountInputWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String accountTag = (String) accountET.getTag();
            if (accountTag != null) {
                if (editable.toString().equals(accountTag)) {
                    String tag = (String) userNameTV.getTag();
                    if (tag != null) {
                        userNameTV.setText(tag);
                    }
                } else {
                    userNameTV.setText("");
                }
            }
        }
    };

    private TextWatcher passwordInputWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() == 0) {
                clearPwd.setVisibility(View.GONE);
            } else {
                clearPwd.setVisibility(View.VISIBLE);
            }
        }
    };
}
